package com.hue.netty.day03.rpc.netty;

import com.hue.netty.day03.rpc.common.HelloService;
import com.hue.netty.day03.rpc.server.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
    //自定义协议时规定发送过来的消息必须以startWith开头
    private String startWith = "nettyrpc#";
    private HelloService helloService = new HelloServiceImpl();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("服务端接收到消息:" + msg);
        if (msg.startsWith(startWith)) {  //发送的消息符合协议
            String result = helloService.hello(msg.substring(startWith.length()));
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
